var GraphControls = function (graph, data){
	var _this = this;
	this.graph = graph;
	this.data = data;
	this.shifted = false;
	this.clicked = false;
	this.hover = false;
	this.click = {dist:0};
	this.scale = {y:500, x:100};
	this.drag = {start:{x:0, y:0},end:{x:0, y:0}};
	this.openDataFile = function(evt) { //PARAST FAILI VALIKU SAAME FAILI SISU
		var text=[];
		var files = evt.target.files; // FileList object
		var file=files[0];
		var reader = new FileReader();
		reader.onload = (
				function() {
					return function(e) { 
							text = e.target.result; 
							_this.data.resOut(text.split("\r"));
							console.log("sec", data.korgMax);

							for(var i=0; i<data.parsed.length; i++){
								_this.boxes(i, data.parsed.length);
							}
							_this.data.setMinMax();
							_this.graph.setVer();
							_this.graph.draw();
							_this.setFreq(_this.data.sagedus);
							//gControls.initShift();
							_this.initShift();
					};
				}
		)();
		reader.readAsText(file);
	 	
		};
	this.skaleeri = function(){
		  $("#subplot").text("0 ms");
          /*******SKALEERIMISNUPUD***********/
          $(".skal").css({"cursor":"pointer"})
          	.hover(_this.hover, _this.hout)
                 .mouseup(function(){_this.graph.skaleerHorRelease();})
                 .mouseout(function (){_this.graph.skaleerHorRelease();});
	    
        $("#skalXzIn")
             .click(function(){_this.graph.skaleerHoriz(-_this.scale.x)})
             .mousedown(function (){_this.graph.skaleerHorCycle(-_this.scale.x)});
        $("#skalXzOut")
             .click(function(){_this.graph.skaleerHoriz(_this.scale.x)})
             .mousedown(function (){_this.graph.skaleerHorCycle(_this.scale.x)});
        $("#skalYzIn")
             .click(function(){
            	 _this.graph.skalVerMax(-_this.scale.y); 
            	 _this.graph.skalVerMin(-_this.scale.y)})
             .mousedown(function (){_this.graph.skalVerCycle(-_this.scale.y)});
        $("#skalYzOut")
             .click(function(){
            	 _this.graph.skalVerMax(_this.scale.y); 
            	 _this.graph.skalVerMin(_this.scale.y)})
             .mousedown(function (){_this.graph.skalVerCycle(_this.scale.y)});
	
        /*******GRAAFIKU MANIPULEERIMISE NUPUD***********/
        $("#niheSuund").click(function(){_this.shiftDirTgl()});
        $("#nihe").change(function(e){_this.setShift(e.target)});
        //disableNihe();
	};
	this.hover = function (e){$(e.target).css({"color":"#0000aa","background-color":"#ddd"});};
	this.hout = function (e){$(e.target).css({"color":"#000","background-color":"transparent"});};
	this.events = function(){
		$(document)
			.keydown(function(e){ if (e.keyCode == 16) _this.shifted = true; })
			.keyup(function(e){ if (e.keyCode == 16) _this.shifted = false; });
		$("#placeholder").mousedown(
				function (e){
					_this.drag.start.x= e.pageX;
					_this.drag.start.y = e.pageY;
					_this.clicked = 1;
					video.seeking = true;
	       });
		$("#placeholder").mousemove(function(e){
			if (!_this.drag.start.x) return;
		    if (!_this.clicked) return;
		    if (_this.shifted){
		    	var hetkY = e.pageY;
		    	var yShift = e.pageY-_this.drag.start.y;
		    	var speedYkf = ((_this.data.korgMax-_this.data.korgMin)*200/56120);
		    	_this.graph.skalVerMax(yShift*speedYkf);
		    	_this.graph.skalVerMin(-yShift*speedYkf);
		    	_this.drag.start.y = hetkY;
		    	_this.graph.draw();
		    	return;
		    }
	        var speedKoef = _this.graph.pikkus/1000;
	        var time= (new Date()).getMilliseconds();
	        if (time%10 == 0) $("#dataHald.korgMin").text(time);
	        if (time%5 == 0){
	        	e.stopPropagation();
	        	var dist= e.pageX-_this.drag.start.x;
	        	$("#graafHald.pikkus").text(dist);
	        	_this.click.dist=(e.pageX-_this.drag.start.x)*-17*speedKoef;
	        	//clickShift=(e.pageX-_this.drag.start.x)*-17*speedKoef;
	        	_this.graph.draw(_this.click.dist);
	          }
	       });
	       $("#placeholder")
				.mouseup  (function(e){_this.stopMovingGraph(e);})
				.mouseout  (function(e){_this.stopMovingGraph(e);});
	       $('#placeholder').bind('mousewheel', 
	    		   	function(e){
			    	   	var zoomIn = -1;
			    	   	if(e.originalEvent.wheelDelta < 0) zoomIn = 1;
			    	   	if (_this.shifted){
			    	   		_this.graph.skalVerMax(_this.scale.y*zoomIn);
			    	   		_this.graph.skalVerMin(_this.scale.y*zoomIn);
			    	   		return;
			    	   	}
			    	   	_this.graph.skaleerHoriz(_this.scale.x*zoomIn);
			    	   	return false;
	       			});
	 $('#sl1').slider();
	    $('#sl1').slider('setValue', 1000);
	    $('#sl1')
	    	.on('slide', function(ev){
	    		if (!this.value) this.value=1000;
	    		if (this.value%2) this.value--;
	    		$("#sl1").slider('setValue', this.value);
	    		_this.graph.pikkus = this.value-0;
	    		_this.graph.draw();
	     });
	};
	this.events();
	
	this.stopMovingGraph = function(e){
		if (_this.shifted) {
			_this.clicked = false;
			_this.graph.draw();
			return;
		}
	//	_this.drag.start.x=0;
		if (_this.clicked){
			video.currentTime+=_this.click.dist/1000;
			_this.graph.draw();
			_this.clicked=false;
			e.stopPropagation();
			_this.drag.end.Y = e.pageX;
			var vahe = _this.drag.end.Y-_this.drag.start.x;
		}
		_this.clicked=0;
	};
	this.boxes = function(id, sensNum){
		 if (_this.data.isNew) { //kui uus data fail on alla laaditud
             $("#curveControls").empty(); //siis kustutame kõverate juhtimisboxi
             _this.data.isNew = false; //lülitame välja uue data faili trigerit
             this.boxes.count=0; // paneme nulliks kõverate arvu
        }
        if (!this.boxes.count) this.boxes.count=0;
        var span=Math.floor(12/sensNum);
        var well = $("<div>").attr({"class" : "span"+span,"id" : "sensDiv"+id}).appendTo($("#curveControls")).css({
                                                     "background-color" : "#faf0f0","padding" : "5px", "font" : "normal 10px Arial"});
        well.append(($("<span>")).text("sensor #"+(id+1)+" ").css("font", "bold 14px Arial"));
        //well.append("sensor #"+(id+1)+"&nbsp;");
        var cb = $("<input>")
        			.attr({"type" : "checkBox","id" : "snsr"+id})
        			.bind('change', this.allBxs)
        			.appendTo(well);
        
        well.append("<br>");
        for (var i=2; i< _this.data.FIELDS_NUM+1; i++){ // 2 - s kakogo stolbca objekta nachat 0-abs.timestamp, 1-node_id, <2- local_timestamp>-deprecated
              if (i>0) well.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
             var nxBox = $("<input>")
             			.attr({
             					"name" : "curve", 
             					"type" : "checkBox",
             					"id" : _this.data.columns[i]+"_"+id+"_"+this.boxes.count,
             					"onchange" : "data.setMinMax();graph.draw()"
             			})
            		 	.appendTo(well);
             if (i==2) { nxBox.prop("checked", true); }
             var label=$("<span>")
             		.attr('id', 'colorSpan'+this.boxes.count)
             		.css('color', this.graph.colors[this.boxes.count])
             		.appendTo(well);
             label.append("&nbsp;"+_this.data.columns[i]+"<br>");
             this.boxes.count++;
        }
	};
	this.allBxs = function(e){
		box = e.target;
		$("#sensDiv"+box.id.replace("snsr", "")+ '  :checkbox').each(function(){
							this.checked = box.checked; 
							this.graph.draw();
						});

	};
	this.getShiftDir = function(){
		return $("#niheSuund").attr('alt')-0;
	};
	this.shiftDirTgl = function(){
		suund = 'forward';
		var setSuund = this.getShiftDir() == 1 ? 0 : 1;
		if (setSuund) suund = 'backward';
		$("#niheSuund").attr('alt', setSuund).empty().append($("<i>").attr("class", 'icon-'+suund));
		this.setShift($("#nihe")[0]);
	};
	this.setShiftDir = function(s){
		suunds = ['forward', 'backward'];
		$("#niheSuund").attr('alt', s).empty().append($("<i>").attr("class", 'icon-'+suunds[s]));
	};
	this.setShift = function(shBox){
		inputStr = $(shBox).val();
		var err=false;
		console.log(inputStr);
		if (isNaN(inputStr)){
			$(shBox).val(inputStr.substring(0, inputStr.length-1));
			$(shBox).attr('placeholder', 'AINULT NUMBRID!');
			err=true;
		}
		$("#nihutamisBox").attr('class', "span7 well form-inline lead");
		if (err || !data.parsed) return false;
		if (this.getShiftDir()) this.graph.nihe=inputStr-0;
		else this.graph.nihe = 0-inputStr;
		$.removeCookie("nihe");
		$.cookie("nihe",this.graph.nihe);
		//alert($.cookie("nihe"));
		this.graph.draw();
		return true;	
	};
	this.initShift = function(){
		if (!data.parsed) return false;
		if (!$.cookie("nihe")) return;
		var boxVal = $.cookie("nihe");
		var back = boxVal < 0;
		console.log(back*1);
		var suunds = ['forward', 'backward'];
		$("#niheSuund").attr('alt', back-0).empty().append($("<i>").attr("class", 'icon-'+suunds[back-0]));
		$("#nihe").val(Math.abs(boxVal));
		$("#nihe").removeAttr("disabled");
		this.setShift($("#nihe")[0]);
		
		
	};
	this.setFreq = function(sagedus){
		$("#sageBox").text(1000/sagedus);
	};
	
   

	
	
	
};